package com.x.erp.manage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.x.erp.dao.CarDao;
import com.x.erp.dao.DetectionDao;
import com.x.erp.dao.UserDao;
import com.x.erp.model.Car;
import com.x.erp.model.CarLog;
import com.x.erp.model.Detection;
import com.x.erp.model.DetectionImage;
import com.x.erp.model.User;
import com.x.erp.payload.DetectionMsg;
import com.x.erp.service.DetectionService;
import com.x.erp.util.ConstantState;
import com.x.erp.util.ConstantTopic;
import com.x.framework.exception.BusinessException;
import com.x.framework.exception.ExceptionCode;
import com.x.framework.manage.BaseManage;
import com.x.rocketmq.RocketMqProducer;

@Service
public class DetectionManage extends BaseManage {

	private static final Logger logger = LoggerFactory.getLogger(DetectionService.class);

	@Autowired
	private DetectionDao detectionDao;// 检测单信息Dao

	@Autowired
	private CarDao carDao;// 车辆Dao

	@Autowired
	private UserDao userDao;// 用户Dao

	@Autowired
	private RocketMqProducer rocketMqProducer;

	/**
	 * 新增检测单信息
	 * 
	 * @param detection
	 * @return
	 * @throws Exception
	 */
	public Detection insertDetection(Detection detection) throws Exception {
		Car car = detection.getCar();
		detection = this.insert(detection);
		if (this.update(car) != 1) {
			throw new BusinessException("新增检测单信息、修改车辆状态出错");
		}
		// 记录日志信息
		List<CarLog> carLogs = car.getCarLogs();
		if (carLogs != null) {
			for (CarLog carLog : carLogs) {
				this.insert(carLog);
			}
		}
		return detection;
	}

	/**
	 * 修改检测单信息
	 * 
	 * @param detection
	 * @return
	 * @throws Exception
	 */
	public int updateDetection(Detection detection) throws Exception {
		if (detection.getDetectionState() == ConstantState.DETECTION_STATE_SEND_ORDER) {
			// 检测状态变为10，生成检测单编号
			String detectionNo = createDetectionNo(detection);
			detection.setDetectionNo(detectionNo);
		}
		int update = this.update(detection);

		try {
			Detection temp = new Detection ();
			temp.setDetectionId (detection.getDetectionId ());
			temp = detectionDao.selectDetection(temp);
			Car car = new Car();
			car.setCarId(temp.getCarId());
			car = carDao.selectCar(car);

			DetectionMsg detectionMsg = new DetectionMsg();
			detectionMsg.setCarId(car.getCarId());
			detectionMsg.setCarTitle(car.getCarTitle());
			detectionMsg.setShopId(car.getShopId());
			// 检测状态
			if (detection.getDetectionState() != null) {
				if (detection.getDetectionState() == ConstantState.DETECTION_STATE_SEND_ORDER) {

					User user = new User();
					user.setUserId(detection.getDetectUserId());
					List<User> selectUserList = userDao.selectUserList(user);
					user = selectUserList.get(0);

					detectionMsg.setDetectorName(user.getUserName());
					detectionMsg.setDetectorMobile(user.getUserMobile());
					produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_DETECTION_STATE_10,
							detectionMsg, "车辆检测已派单");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
		}
		return update;
	}

	/**
	 * 创建检测单编号
	 * 
	 * @param detection
	 * @throws Exception
	 */
	private String createDetectionNo(Detection detection) throws Exception {
		// 检测单格式：市场编号后三位+日期（八位）+检测员编号（三位）+序号（三位） 例子：00120180321ZZC001
		Detection detectionTemp = new Detection();
		detectionTemp.setDetectionId(detection.getDetectionId());
		detectionTemp = detectionDao.selectDetection(detectionTemp);
		StringBuilder detectionNo = new StringBuilder();
		// 市场编号后3位
		String marketCode = detectionTemp.getMarket().getMarketCode();
		String marketCode3 = marketCode.substring(marketCode.length() - 3);
		detectionNo.append(marketCode3);
		// 当前日期8位
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String format = sdf.format(date);
		detectionNo.append(format);
		// 检测员编号3位
		User user = new User();
		user.setUserId(detection.getDetectUserId());
		List<User> selectUserList = userDao.selectUserList(user);
		user = selectUserList.get(0);
		String userNo = user.getUserNo();
		detectionNo.append(userNo.substring(userNo.length() - 3));
		// 序号3位
		int currentNum = detectionDao.selectCurrentNum(detectionTemp, marketCode3 + format + "%");
		String currentNumStr = "000" + currentNum;
		String currentNo = currentNumStr.substring(currentNumStr.length() - 3);
		detectionNo.append(currentNo);
		return detectionNo.toString();
	}

	private void produceRocketMqMessage(String topic, String tag, Object obj, String msg) {
		try {
			rocketMqProducer.produceMessage(topic, tag, obj);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(msg + "异常", e);
		}
	}

	/**
	 * 修改检测单信息（包括图片、车辆状态）
	 * 
	 * @param detection
	 * @return
	 * @throws Exception
	 */
	public int updateDetectionInfo(Detection detection, CarLog carLog) throws Exception {
		int res = this.update(detection);// 修改检测单信息
		if (res != 1) {
			throw new BusinessException("修改检测单信息出错");
		}
		// 处理图片信息
		List<DetectionImage> images = detection.getDetectionImages();
		if (images != null) {
			for (DetectionImage image : images) {
				this.insert(image);
			}
		}
		// 车辆信息
		Car car = new Car();
		car.setCarId(detection.getCarId());
		car.setCarDetectState(ConstantState.CAR_DETECT_STATE_REDETECT_FINISH);// 修改车辆检测状态为检测完毕
		if (this.update(car) != 1) {
			throw new BusinessException("修改检测单信息、修改车辆信息出错");
		}
		// 修改车辆状态，记录日志
		this.insert(carLog);
		// 发送已检测mq消息
		Car selectCar = new Car();
		selectCar.setCarId(detection.getCarId());
		selectCar = carDao.selectCar(selectCar); 
		DetectionMsg detectionMsg = new DetectionMsg();
		detectionMsg.setCarId(selectCar.getCarId());
		detectionMsg.setCarTitle(selectCar.getCarTitle());
		detectionMsg.setShopId(selectCar.getShopId());
		produceRocketMqMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_DETECTION_STATE_20,
				detectionMsg, "车辆检测完毕");
		return res;
	}

}
